/*
 *
 */
package server.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Sérgio C. Peres
 * @author Guilherme Alves
 */
public class HTTPServer {

    private int port;
    private String pathDir;

    public HTTPServer(String pDir, int port) {
        this.setPort(port);
        this.setPathDir(pDir);
    }

    public void setPathDir(String pathDir)
    {
        this.pathDir = pathDir;
    }
    
    public void setPort(int porta) {
        this.port = porta;
    }

    public int getPort()
    {
        return port;
    }

    public String getPathDir()
    {
        return pathDir;
    }
       

    public void run() {
        ServerSocket socketServidor = null;
        System.out.println("Servidor Iniciando…");
        
        try {
            System.out.println("Tentando alocar a porta…");
            socketServidor = new ServerSocket(port);
        } catch (IOException e) {
            System.out.println("Erro Fatal: " + e.getMessage());
            return;
        } catch (Exception e) {
            System.out.println("Erro Fatal: " + e.getMessage());
            return;
        }
        
        System.out.println("Servidor OK!");
        
        while (true) {
            System.out.println("Servidor Aguardando…");
            Socket socket = null;
        
            try {
                socket = socketServidor.accept();
                
                InetAddress infoCliente = socket.getInetAddress();
                System.out.println("\nCliente: " + infoCliente.getHostName() + " conectou ao servidor!");
                System.out.println("=> "+socket.getPort());
                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                DataOutputStream output = new DataOutputStream(socket.getOutputStream());
                
                HTTPRequest clientReq = new HTTPRequest();
                clientReq.httpHandler(input, output);
                
                HTTPResponse res = new HTTPResponse(this, output);
                if (res.setRequest(clientReq))
                {
                    res.sendResponse();
                    
                    System.out.println(clientReq.getHeader());
                }
                output.close();
                input.close();                
                
                socket.close();
            } catch (IOException e) {
                System.out.println("Erro de conexão: " + e.getMessage());
                break;
            }
        }
    }
}
